const fs = require("fs");
const path = require("path");
const http = require("http");
const https = require("https");
const url = require("url");
const buffer = require("buffer");
const randomstring = require("randomstring");
const rp = require("request-promise-native");
const FormData = require("form-data");

const upload_url = "https://mp.sohu.com/commons/upload/file";
const parsed_url = url.parse(upload_url);

/**
 * 
 * @param {String} full_path 
 * @returns {Promise<{ok:Boolean,msg:String,url:Strings}>}
 */
function uploadSingle(full_path) {
  return new Promise(async (resolve, reject) => {
    let file_stream = fs.createReadStream(full_path);
    let ext_name = path.extname(full_path);

    let form = new FormData();

    form.append("file", file_stream, {
      filename: `${randomstring.generate(5)}.png`,
      contentType: "image/png"
    })

    // form.pipe(fs.createWriteStream("form-data-debug.txt"));
    // return;

    form.submit({
      host: parsed_url.host,
      path: parsed_url.path,
      protocol: parsed_url.protocol,
      headers: {
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36",
        'x-requested-with': 'XMLHttpRequest',
        'referer': 'https://mp.sohu.com/mpfe/v3/create/step3/person'
      }
    }, (err, res) => {
      if (err) {
        return resolve({
          ok: false,
          msg: err.message,
          url: ""
        })
      }
      if (res.statusCode != 200) {
        return resolve({
          ok: false,
          msg: `HTTP ${res.statusCode} ${res.statusMessage}`,
          url: ""
        })
      }
      let buf = new buffer.Buffer("");
      res.on("data", (chunk) => {
        buf += chunk;
      });
      res.on("end", () => {
        try {
          let j = JSON.parse(buf);
          if (!j['url']) {
            return resolve({
              ok: false,
              msg: `result.url is ${j['url']},result is ${j}`,
              url: ""
            })
          }
          console.log(path.basename(full_path));
          console.log(j['url']);
          resolve({
            ok: true,
            msg: "ok",
            url: j['url']
          })
        } catch (e) {
          return resolve({
            ok: false,
            msg: error,
            url: ""
          })
        }
      })
    });
  })
}
/**
 * @param {Number} x
 * @param {String} full_path 
 */
function uploadSingleForXTime(x, full_path) {
  let g = (function* () {
    for (let i = 1; i <= x; i++) {
      yield uploadSingle(full_path);
    }
  })();
  let it = g.next();
  return new Promise((resolve, reject) => {
    (function bootstrap() {
      if (it.done) {
        reject(x + "times failed");
      } else {
        it.value.then(() => {
          resolve();
        }).catch(e => {
          it = g.next();
          bootstrap();
        })
      }
    })();
  })
}




if (!module.parent) {
  uploadSingle(path.join(__dirname, "../test.txt"));
}

module.exports = {
  uploadSingleForXTime: uploadSingleForXTime
}